'use strict';

import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import * as actions from '../../actions/home';
import {Dialog,Field,Form,Input,Pagination,Tab,Notice,Button,Icon,Select} from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import SystemDialog from 'components/system-dialog/index';
import ImageSelector from 'components/ImageSelector/index';


class Home extends React.Component {
	constructor(props) {
		super(props);
		this.field = new Field(this, {
			scrollToFirstError:true,
			onChange: (name, value) => {
					this.setState({overlayVisible:false});
			}
		});
		this.state = {
			showDialog:false,
			showPagePubError:false,
			showDelete:"false",
			showPicDialog:false,
			showEditDialog:false,
		}
		this.dispatch = this.props.dispatch; 
		this.dispatch(
			actions.getPages({
				is_delete:"false",
				page:1,
				page_size:this.props.home.pageSize
			})
		);
	} 
	closeSystemDialog(){
	  this.dispatch(
			actions.closeSystemDialog()
	  );
	}
	handlePageChange(page){
		this.dispatch(
			actions.getPages({
				is_delete:this.state.showDelete,
				page:page,
				page_size:this.props.home.pageSize
			})
		);
	}
	handleRemovePage(page_id){
		Dialog.confirm({
			content: '确定要删除这个页面吗？',
			closable: false,
			onOk: () => {
				this.dispatch(
					actions.removePage({page_id})
				)
			}
		});
	}
	handlePagePublish(page_id){
		Dialog.confirm({
			content: '发布页面需要一点时间，请耐心等待',
			closable: false,
			onOk: () => {
				this.dispatch(
					actions.publishPage({page_id})
				)
			}
		});
	}
	handlePagePubing(){
		Dialog.alert({
			content:"页面正在发布，请耐心等待"
		});
	}
	handlePageUnpub(page_id){
		Dialog.confirm({
			content: '下线页面需要一点时间，请耐心等待。确定要下线这个页面吗？',
			closable: false,
			onOk: () => {
				this.dispatch(
					actions.unPubPage({page_id})
				)
			}
		});
	}
	handlePageShowPubError(page_id){
		this.dispatch(
			actions.getPagePubError({page_id})
		);
		this.setState({showPagePubError:true,page_id});
	}
	showDialog(short_url,url,qrcode_url){
		this.setState({showDialog:true,short_url,url,qrcode_url});
	}
	closeDialog(){
		this.setState({showDialog:false,short_url:"",url:"",qrcode_url:""});
	}
	closePagePubErrorDialog(){
		this.setState({showPagePubError:false});
	}
	rePubPage(){
		Dialog.confirm({
			content: '您需要重新发布这个页面吗？',
			closable: false,
			onOk: () => {
				Dialog.alert({
					content:"请修复所有错误后点击“已下线”按钮"
				});
				this.dispatch(
					actions.unPubPage({page_id:this.state.page_id})
				)
			}
		});
		this.setState({showPagePubError:false});
	}
	handleResetPage(page_id){
		this.dispatch(
			actions.unPubPage({page_id})
		)
	}
	showDeletedPage(page){
		this.setState({showDelete:"true"});
		this.dispatch(
			actions.getPages({
				is_delete:"true",
				page:page,
				page_size:this.props.home.pageSize
			})
		);
	}
	showAllPage(page){
		this.setState({showDelete:"false"});
		this.dispatch(
			actions.getPages({
				is_delete:"false",
				page:page,
				page_size:this.props.home.pageSize
			})
		);
	}
	saveAsModelDialog(page){
		this.field.setValues({"name":page.name,"preview":page.preview,"qrcode":page.qrcode_url});
		this.setState({"saveAsModelDialog":true,"saveAsModelPage":page.id});
	}
	closeSaveAsModelDialog(){
		this.setState({"saveAsModelDialog":false});
	}
	saveAsModel(){
		let vals = this.field.getValues();
		this.dispatch(
			actions.saveAsModel({...vals,
				page_id:this.state.saveAsModelPage,
			})
		);
	}
	editPageTitle(){
		this.dispatch(
			actions.editPageTitle({
				page_id:this.state.curPageId,
				name:this.state.curPageName,
				preview:this.state.curPagePreview
			})
		);
		this.setState({"showEditDialog":false});
	}
	editTitle(page){
		this.setState({"curPageId":page.id,"curPageName":page.name,"curPagePreview":page.preview,"showEditDialog":true});
	}
	closeEditDialog(){
		this.setState({"showEditDialog":false});
	}
	onUploadError(err,res){
		Dialog.alert({content:"上传图片错误！请重试"});
	}	
	saveSelectedImage(res){
		const picUrl = res.picture.picture_path;
		this.field.setValue("preview",picUrl);
		this.setState({curPagePreview:picUrl,showPicDialog:false});
	}
  render() {
	const init = this.field.init;
	const pages = this.props.home.pages;
	let createPage = "";
	let noPage="";
	if(this.props.home.total==0){
			noPage = 
			<Col>
				<div>
					<Row justify="center" style={{marginTop:"50px"}}>
						<img src="https://img.alicdn.com/imgextra/i4/27390555/TB2NXB8bMkLL1JjSZFpXXa7nFXa-27390555.png" style={{width:"160px",height:"175px"}}/>
					</Row>
					<Row justify="center">
						<p>当前暂无活动页面</p>
					</Row>
					<Row justify="center">
						<Link to="/models">
							<Button type="secondary">创建页面</Button>
						</Link>
					</Row>
				</div>
			</Col>;
	}else{
			createPage=
					<Link to="/models">
						<Button shape="warning" size="large">创建页面</Button>
					</Link>
	}
    return <div className="home-page">
				<SystemDialog 
					loginError={this.props.home.loginError}	
					creating={this.props.home.creating}
					message={this.props.home.message}
					error={this.props.home.error}
					onClose={this.closeSystemDialog.bind(this)}
					/>
				<Dialog visible={this.state.showPagePubError}
						onOk={this.rePubPage.bind(this)}
						onCancel={this.closePagePubErrorDialog.bind(this)}
						onClose={this.closePagePubErrorDialog.bind(this)} 
						title="查看出错信息"
						>
						{
							this.props.home.msg_list.map((msg)=>{
								return(
								<Row justify="start">
									{msg.msg}{msg.date}
								</Row>);
							})
						}
				</Dialog>
				<Dialog visible={this.state.showDialog}
						onOk={this.closeDialog.bind(this)}
						onCancel={this.closeDialog.bind(this)}
						onClose={this.closeDialog.bind(this)} 
						title="请复制链接"
						footer={false}
						>
						<Row justify="center">
							短链接：<Input value={this.state.short_url} />
						</Row>
						<Row justify="center" style={{marginTop:"10px"}}>
							长链接：<Input value={this.state.url} />
						</Row>
						<Row justify="center" style={{marginTop:"10px"}}>
							二维码：<Input value={this.state.qrcode_url} />
						</Row>
						<Row justify="center" style={{marginTop:"10px"}}>
							<img src={this.state.qrcode_url} width="100" height="100" />
						</Row>
				</Dialog>
				
				<Dialog visible={this.state.showEditDialog}
						onOk={this.editPageTitle.bind(this)}
						onCancel={this.closeEditDialog.bind(this)}
						onClose={this.closeEditDialog.bind(this)} 
						title="修改标题和缩略图"
						>
						<Row style={{marginTop:"10px"}}>
							<Col span="7">标题：</Col>
							<Col><Input value={this.state.curPageName} onChange={(v)=>{this.setState({curPageName:v})}} /></Col>
						</Row>
						<Row style={{marginTop:"10px"}}>
							<Col span="7">预览图：</Col>
							<Col><img src={this.state.curPagePreview} width="100"  /></Col>
							<Col><Button onClick={()=>{this.setState({"showPicDialog":true});}}>选择</Button></Col>
						</Row>
				</Dialog>
				<Dialog visible={this.state.saveAsModelDialog}
						onOk={this.saveAsModel.bind(this)}
						onCancel={this.closeSaveAsModelDialog.bind(this)}
						onClose={this.closeSaveAsModelDialog.bind(this)} 
						title="保存为模板"
						style={{width:"700px"}}
						>
							<Row style={{marginTop:"10px"}}>
								<Col fixSpan="4">价格v1：</Col>
								<Col><Input style={{width:"100px"}} {...init('price_v1',{initValue:'0'})} /></Col>
								<Col fixSpan="4">代码v1：</Col>
								<Col><Input style={{width:"100px"}} {...init('item_code_v1')} /></Col>
								<Col fixSpan="4">类目：</Col>
								<Col><Input style={{width:"100px"}} {...init('catgory')} /></Col>
							</Row>
							<Row style={{marginTop:"10px"}}>
								<Col fixSpan="4">价格v2：</Col>
								<Col><Input style={{width:"100px"}} {...init('price_v2',{initValue:'0'})} /></Col>
								<Col fixSpan="4">代码v2：</Col>
								<Col><Input style={{width:"100px"}} {...init('item_code_v2')} /></Col>
								<Col fixSpan="4">颜色：</Col>
								<Col>                
									<Select.Combobox {...init('tag_color')} style={{width:"100px"}}>
										<Option value="">空</Option>
										<Option value="red">红色</Option>
										<Option value="orange">橙色</Option>
										<Option value="blue">蓝色</Option>
										<Option value="gray">灰色</Option>
										<Option value="black">黑色</Option>
										<Option value="purple">紫色</Option>
										<Option value="green">绿色</Option>
										<Option value="white">白色</Option>
										<Option value="brown">棕色</Option>
										<Option value="yellow">黄色</Option>
									</Select.Combobox>
								</Col>
							</Row>
							<Row style={{marginTop:"10px"}}>
								<Col fixSpan="4">价格v3：</Col>
								<Col><Input style={{width:"100px"}} {...init('price_v3',{initValue:'0'})} /></Col>
								<Col fixSpan="4">代码v3：</Col>
								<Col><Input style={{width:"100px"}} {...init('item_code_v3')} /></Col>
								<Col fixSpan="4">节日：</Col>
								<Col>
									<Select.Combobox {...init('tag_time_nodes')} style={{width:"100px"}}>
										<Option value="">空</Option>
										<Option value="double_11">双11</Option>
										<Option value="spring_festival">春节·年货节</Option>
										<Option value="mid_autumn_day">中秋节</Option>
										<Option value="valentines_day">情人节</Option>
										<Option value="national_day">10·1国庆</Option>
										<Option value="drinks_festival">9·9酒水节</Option>
										<Option value="66_festival">淘宝66大促</Option>
										<Option value="618_festival">天猫618理想生活节</Option>
										<Option value="labor_day">5·1大促</Option>
										<Option value="newyear_day">元旦</Option>
										<Option value="women_day">3·8女人节</Option>
										<Option value="lantern_festival">元宵节</Option>
										<Option value="qixi_day">七夕节</Option>
										<Option value="april_fools_day">愚人节</Option>
										<Option value="qingming_festival">清明节</Option>
										<Option value="double_fifth_day">端午节</Option>
										<Option value="double_ninth_day">重阳节</Option>
										<Option value="winter_solstice">冬至</Option>
										<Option value="mothers_day">母亲节</Option>
										<Option value="fathers_day">父亲节</Option>
										<Option value="childrens_day">儿童节</Option>
										<Option value="teachers_day">教师节</Option>
										<Option value="kissing_day">7·6接吻日</Option>
										<Option value="easter_day">复活节</Option>
										<Option value="halloween">万圣节</Option>
										<Option value="thanksgiving_day">感恩节</Option>
										<Option value="christmas_day">圣诞节</Option>
										<Option value="bestie_day">3·1-3·7闺蜜节</Option>
										<Option value="gastronomes_day">517吃货节</Option>
										<Option value="cars_day">518-618购车节</Option>
										<Option value="babys_day">518母婴节</Option>
										<Option value="aegyo_day">81日-816撒娇节</Option>
										<Option value="anniversary_day">店庆</Option>
									</Select.Combobox>
								</Col>
							</Row>
							<Row style={{marginTop:"10px"}}>
								<Col fixSpan="4">价格v4：</Col>
								<Col><Input style={{width:"100px"}} {...init('price_v4',{initValue:'0'})} /></Col>
								<Col fixSpan="4">代码v4：</Col>
								<Col><Input style={{width:"100px"}} {...init('item_code_v4')} /></Col>
								<Col fixSpan="4">营销：</Col>
								<Col>
									<Select.Combobox {...init('tag_action')} style={{width:"100px"}}>
										<Option value="">空</Option>
										<Option value="countdown_prom">倒计时折扣</Option>
										<Option value="countdown_prom_code">营销码</Option>
										<Option value="limit_prom">限时促销</Option>
										<Option value="lottery">抽奖</Option>
										<Option value="gift">赠品</Option>
										<Option value="coupon">优惠券</Option>
									</Select.Combobox>
								</Col>
							</Row>
							<Row style={{marginTop:"10px"}}>
								<Col fixSpan="4">价格v5：</Col>
								<Col><Input style={{width:"100px"}} {...init('price_v5',{initValue:'0'})} /></Col>
								<Col fixSpan="4">代码v5：</Col>
								<Col><Input style={{width:"100px"}} {...init('item_code_v5')} /></Col>
								<Col fixSpan="4">备注：</Col>
								<Col><Input style={{width:"100px"}} {...init('info')} /></Col>
							</Row>
							<Row style={{marginTop:"10px"}}>
								<Col fixSpan="4">缩略图：</Col>
								<Col><Input style={{width:"100px"}} {...init('preview')} /><Button onClick={()=>{this.setState({"showPicDialog":true});}}>选</Button></Col>
								<Col fixSpan="4">名称：</Col>
								<Col><Input style={{width:"100px"}} {...init('name')} /></Col>
								<Col fixSpan="4">二维码：</Col>
								<Col><Input style={{width:"100px"}} {...init('qrcode')} /></Col>
							</Row>
							<Row>
							<img src={this.field.getValue("preview")} style={{height:"100px"}} />
							</Row>
				</Dialog>
				<ImageSelector 
					maxPic={1}
					minPicSize={{"width":40,"height":40}}
					showPicDialog={this.state.showPicDialog}
					onClose={()=>{this.setState({"showPicDialog":false})}}
					onUploadSuccess={this.saveSelectedImage.bind(this)}
					onUploadError={this.onUploadError.bind(this)}
					defaultPicType="upload"
					selectorStyle={{"width":"1100px"}}
					aspectRatio={750/1000}
					onlyCrop={false}
					cropperDialogStyle={{"width":"1000px"}}
					copperStyle={{"height":"420px"}}
					uploadServer={window.img_upload_server}
					previewList={["300x168"]}
					userNick={window.info.user_nick}
					pageSize={32}
					>
				</ImageSelector>
				<Row justify="end">
					<Button size="large" onClick={this.showAllPage.bind(this,1)}>正常页面</Button>
					&nbsp;
					<Button size="large" onClick={this.showDeletedPage.bind(this,1)}>回收站</Button>
					&nbsp;
					{createPage}
				</Row>
				<Row type="wrap" align="center" style={{border:"1px dashed #999999",borderRadius:"20px",padding:"20px",marginTop:"10px"}}>
				{noPage}
				{
					pages.map((page,key)=>{
						let pubBtn = "发布状态";
						let pubText = "发布状态";
						let adminBtn = "";
						let style = {};
						if(page.status=="normal"){
							pubBtn = <Button type="primary" onClick={this.handlePagePublish.bind(this,page.id)}>发布</Button>;
							pubText = "未发布";
						}
						if(page.status=="pubing"){
							pubBtn = <Button type="primary" shape="warning" onClick={this.handlePagePubing.bind(this)}>发布中</Button>;
							pubText = "正在发布";
						}
						if(page.status=="pubed"){
							pubBtn = <Button type="normal" shape="warning" onClick={this.handlePageUnpub.bind(this,page.id)}>在线上</Button>;
							pubText = "在线上";
						}
						if(page.status=="offline"){
							pubBtn = <Button type="secondary"  onClick={this.handlePagePublish.bind(this,page.id)}>已下线</Button>;
							pubText = "已下线";
						}
						if(page.status=="error"){
							pubBtn = <Button type="primary" shape="warning"  onClick={this.handlePageShowPubError.bind(this,page.id)}>出错</Button>;
							pubText = "出错";
						}
						if(page.status=="delete"){
							pubBtn = <Button  onClick={this.handleResetPage.bind(this,page.id)}>恢复</Button>;
							pubText = "已删除";
							style = {WebkitFilter:"grayscale(100%)"};
						}
						if(window.info.user_nick=="kekydream"){
							adminBtn = <Button size="small" onClick={this.saveAsModelDialog.bind(this,page)} style={{position:"absolute"}}>转为模板</Button>;
						}
						return (
							<Col key={key}  style={{borderBottom:"1px dotted #999999",marginBottom:"5px",padding:"5px"}} >
								<Col fixedSpan="6" >
									{adminBtn}
									<img style={style} src={page.preview} width="75" height="100" />
								</Col>
								<Col  justify="start" fixedSpan="6">
									{page.name}<Icon type="edit" style={{cursor:"pointer"}} onClick={this.editTitle.bind(this,page)} />
								</Col>
								<Col>
									<Row type="wrap" style={{height:"80px"}}>
										<Row>
											<Col>
											状态：{pubText}
											</Col>
											<Col>
											访客：
											</Col>
										</Row>
									</Row>
									<Row>
										<Col fixedSpan="12">
											<Button onClick={this.showDialog.bind(this,page.short_url,page.url,page.qrcode_url)}>查看二维码</Button>
											&nbsp;
											<a href={window.dnd+"?page_id="+page.id}>
												<Button>编辑</Button>
											</a>
											&nbsp;
											{pubBtn}
										</Col>
										<Col fixedSpan="2">
											<Icon type="close"  
											  style={{cursor:"pointer"}}
											  onClick={this.handleRemovePage.bind(this,page.id)}
											  />
										</Col>
									</Row>
								</Col>
							</Col>
						)
					})
				}
				</Row>
			<Row justify="center" style={{marginTop:"10px"}}>
				<Pagination onChange={this.handlePageChange.bind(this)} defaultCurrent={this.props.home.curPage} pageSize={this.props.home.pageSize} total={this.props.home.total} size="small" />
			</Row>
    </div>;
  }
}

export default connect((state)=> {
  return {
    home: state.home
  };
})(Home);
